﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FUSE.AzureConfig.Tasks
{
    public class AzureConfigGen : Microsoft.Build.Utilities.Task
    {
        public string ConfigurationFile { get; set; }

        public string ConfigurationDirectory { get; set; }

        public string OutputDirectory { get; set; }

        public override bool Execute()
        {
            if (string.IsNullOrEmpty(this.ConfigurationFile))
                throw new ArgumentNullException("Must specify ConfigurationFile");

            if (!string.IsNullOrEmpty(this.OutputDirectory) && !Directory.Exists(this.OutputDirectory))
                throw new ArgumentException(this.OutputDirectory + " output directory must exist if specified");

            this.OutputDirectory = this.OutputDirectory ?? this.ConfigurationDirectory;

            if (!string.IsNullOrEmpty(this.ConfigurationDirectory))
            {
                if (!Directory.Exists(this.ConfigurationDirectory))
                    throw new ArgumentException(this.ConfigurationDirectory + " must exist.");
                if (!Path.IsPathRooted(this.ConfigurationFile))
                    this.ConfigurationFile = Path.Combine(this.ConfigurationDirectory, this.ConfigurationFile);
            }
            if (!File.Exists(this.ConfigurationFile))
                throw new ArgumentException(this.ConfigurationFile + " does not exist");

            AzureConfigSpec confSpec;
            try
            {
                confSpec = JsonConvert.DeserializeObject<AzureConfigSpec>(File.ReadAllText(this.ConfigurationFile));
            } catch (Exception e)
            {
                throw new ArgumentException("Failed to parse " + this.ConfigurationFile, e);
            }

            var conf = new SpecProcessor().Process(confSpec);
            var generator = new FileGenerator();
            generator.AlterCsdef(conf, this.ConfigurationDirectory, this.OutputDirectory);
            generator.AlterCscfgs(conf, this.ConfigurationDirectory, this.OutputDirectory);

            return true;
        }
    }
}
